package leetcode100;

import java.util.*;

public class lc022 {

    /**
     * map, 存储每个结点的深度,从上到下1开始
     *
      */
    static Map<TreeNode,Integer> map = new HashMap<>();
    static int maxDiameter=0;

    public static void main(String[] args) {
        Tree tree = new Tree();
        TreeNode root  = tree.root;
        int res = diameterOfBinaryTree(root);
        System.out.println("maxDiameter: "+res);

    }

    public static int diameterOfBinaryTree(TreeNode root) {
        postorderTraversal(root);
        return maxDiameter;
    }

    public static void calculateDepth(TreeNode node) {
        int leftDepth = map.getOrDefault(node.left,0);
        int rightDepth  = map.getOrDefault(node.right,0);
        maxDiameter=Math.max(maxDiameter,leftDepth+rightDepth);
        int depth = Math.max(leftDepth,rightDepth)+1;
        map.put(node,depth);
    }


    public static void postorderTraversal(TreeNode root) {

        Deque<TreeNode> stack = new LinkedList<>();
        TreeNode prev = null; // 记录上一个访问的节点
        TreeNode curr = root;

        while (curr != null || !stack.isEmpty()) {
            // 1. 遍历左子树，将所有左节点入栈
            while (curr != null) {
                stack.push(curr);
                curr = curr.left;
            }

            // 2. 获取栈顶节点（当前待处理节点）
            curr = stack.peek();

            // 3. 判断右子树是否已处理：
            //    - 右子树为空，直接处理当前节点
            //    - 右子树已访问过（prev是右子节点），处理当前节点
            if (curr.right == null || curr.right == prev) {
                calculateDepth(curr);
                stack.pop(); // 弹出已处理节点
                prev = curr; // 更新上一个访问节点
                curr = null; // 重置curr，避免重复入栈左子树
            } else {
                // 4. 右子树未处理，先处理右子树
                curr = curr.right;
            }
        }
    }
}
